package com.hjxr.quota.define.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjxr.quota.define.domain.QuotaDimRelationDetail;
import com.hjxr.quota.define.domain.QuotaSource;
import com.hjxr.quota.define.domain.QuotaValue;
import com.hjxr.quota.define.domain.vo.DimensionRootVo;
import com.hjxr.quota.define.mapper.QuotaDimRelationDetailMapper;
import com.hjxr.quota.define.mapper.QuotaSourceMapper;
import com.hjxr.quota.define.mapper.QuotaValueMapper;
import com.hjxr.quota.define.service.IQuotaDimRelationDetailService;
import com.hjxr.quota.datasource.domain.ColnameAlias;
import com.hjxr.quota.datasource.domain.QuotaDimension;
import com.hjxr.quota.datasource.domain.QuotaDimensionDetail;
import com.hjxr.quota.datasource.mapper.ColnameAliasMapper;
import com.hjxr.quota.datasource.mapper.QuotaDimensionDetailMapper;
import com.hjxr.quota.datasource.mapper.QuotaDimensionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 预指标与维度（具体维度）关系表 服务实现类
 * </p>
 *
 * @author ma
 * @since 2020-10-16
 */
@Service
public class QuotaDimRelationDetailServiceImpl extends ServiceImpl<QuotaDimRelationDetailMapper, QuotaDimRelationDetail> implements IQuotaDimRelationDetailService {
    @Autowired
    private QuotaValueMapper quotaValueMapper;
    @Autowired
    private QuotaDimensionDetailMapper quotaDimensionDetailMapper;
    @Autowired
    private ColnameAliasMapper colnameAliasMapper;
    @Autowired
    private QuotaDimensionMapper quotaDimensionMapper;
    @Autowired
    private QuotaSourceMapper quotaSourceMapper;
    @Resource
    private QuotaDimRelationDetailMapper quotaDimRelationDetailMapper;

    @Override
    public List<Integer> commonDims(List<Integer> ids) {
        List<Integer> dimIdList = new ArrayList<>();
        for (Integer id : ids) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("quota_id", id);
            List<QuotaDimRelationDetail> quotaDimRelationDetails = list(queryWrapper);
            List<Integer> list = quotaDimRelationDetails.stream().map(QuotaDimRelationDetail::getDimensionId).collect(Collectors.toList());
            for (Integer i : list) {
                dimIdList.add(i);
            }
        }
        List<Integer> dimIdListNew = dimIdList.stream().distinct().collect(Collectors.toList());
        return dimIdListNew;

    }

    @Override
    public Float computeValue(Map<Integer, List<Integer>> parms) {
        //指标值表若可以查到则直接返回 若查不到则计算
        for (Integer id : parms.keySet()) {
            Map<String, Object> map = new HashMap<>();
            List<String> fieldName = new ArrayList<>();//用于存储维度id对应字段名称
            List<Integer> dimIdList = parms.get(id);//获取维度id列表
            List<String> dimList = dimIdList.stream().map(s -> (s.toString())).collect(Collectors.toList());//将取维度id列表List<Integer>转为List<string>
            QueryWrapper<QuotaValue> queryWrapper = new QueryWrapper();
            queryWrapper.eq("quota_id", id);
            List<QuotaValue> quotaValueList = quotaValueMapper.selectList(queryWrapper);
            //查询指标值表是否存在相同指标，若存在直接返回指标值
            for (QuotaValue quotaValue : quotaValueList) {
                List<String> dims = Arrays.asList(quotaValue.getDimensions().split(","));
                //使用list自带的sort方法先进性排序，然后转成toString去判断两个集合是否相等
                dimList.sort(Comparator.comparing(String::hashCode));
                dims.sort(Comparator.comparing(String::hashCode));
                if (dimList.toString().equals(dims.toString())) {//判断集合是否相等
                    return quotaValue.getValue();
                }

            }
            //指标值表中不存在 则计算指标值
            for (Integer dimId : dimIdList) {
                //在维度详细-字段关联表中查找维度id对应数据字段别名表id
                QueryWrapper<QuotaDimensionDetail> queryWrapper1 = new QueryWrapper();
                queryWrapper1.eq("dimension_id", dimId);
                Integer colnameAliasId = quotaDimensionDetailMapper.selectOne(queryWrapper1).getColnameId();
                //根据数据字段别名表id查找字段名称
                QueryWrapper<ColnameAlias> queryWrapper2 = new QueryWrapper();
                queryWrapper2.eq("id", colnameAliasId);
                String columnName = colnameAliasMapper.selectOne(queryWrapper2).getColumnName();
                QuotaDimension quotaDimension = quotaDimensionMapper.selectById(dimId);//根据维度id获得维度名称
                if (quotaDimension == null) {
                    return null;
                }
                map.put(columnName, quotaDimension.getDimensionName());
            }
            QueryWrapper<QuotaSource> quotaWrapper = new QueryWrapper<>();
            quotaWrapper.eq("QUOTA_ID", id);
            QuotaSource quotaSource = quotaSourceMapper.selectOne(quotaWrapper);//根据指标id查询到指标来源表数据
            List<Float> valueList = quotaValueMapper.computeValueF(map, quotaSource.getSTable(), quotaSource.getSCol());

            if (valueList.size() == 1) {
                //只有一条值
                return valueList.get(0);
            } else if (valueList.size() == 0) {
                //无此指标值  不做处理为空
                return null;
            } else {
                //有多条值
                float sum = 0;
                for (Float num : valueList) {
                    sum = sum + num;
                }
                return sum;
            }
        }
        return null;
    }

    @Override
    public List<String> queryUpperDim(List<Integer> dimIds) {
        List<String> list = new ArrayList<>();
        for (Integer dimId : dimIds) {
            QuotaDimension quotaDimension = quotaDimensionMapper.selectById(dimId);
            list.add("(" + queryUpperDimName(dimId) + ")" + quotaDimension.getDimensionName());
        }
        return list;
    }

    private String queryUpperDimName(Integer dimId) {

        QuotaDimension quotaDimension = quotaDimensionMapper.selectById(dimId);
        if (quotaDimension.getUpperId() != 0) {
            int id = quotaDimension.getUpperId();
            return queryUpperDimName(id);
        } else {
            return quotaDimension.getDimensionName();

        }
    }

    @Override
    public List<DimensionRootVo> getDimsByQuotaId(Integer quotaId) {
        //查询指标下的维度 这里不是一级维度
        List<DimensionRootVo> dimensionRootVos = quotaDimRelationDetailMapper.selectDimensionNameByQuotaId(quotaId);
        return dimensionRootVos;
    }

    @Override
    public List<DimensionRootVo> getBeMixedRoot(List<Integer> quotaIds) {
        //查询多指标的公共维度
        List<DimensionRootVo> dimensionRootVos = quotaDimRelationDetailMapper.selectBeMixed
                (quotaIds.get(0), quotaIds.size() > 1 ? quotaIds.subList(1, quotaIds.size()) : null);

        if (dimensionRootVos == null || dimensionRootVos.size() <= 0) {
            return new ArrayList<>();
        }
        Set<Integer> rootIds = dimensionRootVos.stream().map(DimensionRootVo::getRootId).collect(Collectors.toSet());
        List<QuotaDimension> quotaDimensions = quotaDimensionMapper.selectBatchIds(rootIds);
        dimensionRootVos.clear();
        for (QuotaDimension quotaDimension : quotaDimensions) {
            DimensionRootVo dimensionRootVo = new DimensionRootVo();
            dimensionRootVo.setRootId(quotaDimension.getId());
            dimensionRootVo.setRootName(quotaDimension.getDimensionName());
            dimensionRootVos.add(dimensionRootVo);
        }
        return dimensionRootVos;
    }

    @Override
    public List<DimensionRootVo> getBeMixedList(List<Integer> quotaIds) {
        //查询多指标的公共维度
        List<DimensionRootVo> dimensionRootVos = quotaDimRelationDetailMapper.selectBeMixed
                (quotaIds.get(0), quotaIds.size() > 1 ? quotaIds.subList(1, quotaIds.size()) : null);
        if(dimensionRootVos!=null&&dimensionRootVos.size()>0){
            //组装维度名字
            List<Integer> dimIds =
                    dimensionRootVos.stream().map(DimensionRootVo::getDimensionId).collect(Collectors.toList());
            Set<Integer> rootIds = dimensionRootVos.stream().map(DimensionRootVo::getRootId).collect(Collectors.toSet());
            dimIds.addAll(rootIds);
            Map<Integer, QuotaDimension> dimensionMap = quotaDimensionMapper.selectBatchIds(dimIds)
                    .stream().collect(Collectors.toMap(QuotaDimension::getId, a -> a, (k1, k2) -> k1));
            dimensionRootVos.forEach(item -> {
                Integer key = item.getDimensionId();
                if (null != key) {
                    QuotaDimension dimension = dimensionMap.get(key);
                    item.setDimensionName(dimension.getDimensionName());
                } else {
                    key = item.getRootId();
                    QuotaDimension dimension = dimensionMap.get(key);
                    item.setRootName(dimension.getDimensionName());
                }
            });
        }
        return dimensionRootVos;
    }

    @Override
    public List<QuotaDimension> getBeMixedTree(List<Integer> quotaIds) {
        List<QuotaDimension> result = new ArrayList<>();
        //查询多指标的公共维度
        List<Integer> dimIds = quotaDimRelationDetailMapper.selectBeMixedReturnId
                (quotaIds.get(0), quotaIds.size() > 1 ? quotaIds.subList(1, quotaIds.size()) : null);
        if(dimIds!=null&&dimIds.size()>0){
            result = this.quotaDimRelationDetailMapper.selectRootNodeTree(dimIds);
        }
        return result;
    }
}
